penalize.near.exact <- function (net.layers, near.exact) 
{
  oldcost <- net.layers$cost
  startn <- net.layers$startn
  endn <- net.layers$endn
  tcarcs <- net.layers$tcarcs
  theta <- net.layers$theta
  z <- net.layers$z
  newcost <- oldcost
  if (any(startn[-c(1:tcarcs)] %in% which(z == 1))) {
    bypass.edges <- startn %in% which(z == 1)
    bypass.edges[1:tcarcs] <- FALSE
    old.byp.pen <- oldcost[which(bypass.edges)[1]]
    newcost[which(bypass.edges)] <- old.byp.pen * theta
    near.exact.pen <- old.byp.pen
  }
  else {
    #### Modify code such that the near exact penalty is NOT more important than the first level of the RCB hierarchy. ####
    temp_max <- sort(net.layers$penalties, decreasing=T)[1]
    temp_second_max <- sort(net.layers$penalties, decreasing=T)[2]
    
    # near.exact.pen <- theta * max(net.layers$penalties, 0)
    near.exact.pen <- theta * max((temp_max + temp_second_max)/2,0)
    
    if (near.exact.pen == 0) 
      near.exact.pen <- theta * net.layers$p
  }
  newcost[which(near.exact[startn] != near.exact[endn])] <- newcost[which(near.exact[startn] != 
                                                                            near.exact[endn])] + near.exact.pen
  net.layers$cost <- newcost
  return(net.layers)
}